package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        //先获取用户的手机号
        String phone = user.getPhone();

        if(StrUtil.isNotEmpty(phone)){
            //随机生成六位验证码

            String code = RandomUtil.randomNumbers(6);
            System.out.println(code);
            //生成验证码后，要给用户发送验证码
            //调用封装好的工具类
            //AliyunSmsUtil.sendSms(phone,code);
            //发送完验证码要存到session中，因为还要和之后用户发来的验证码、
            //进行校验
            session.setAttribute(phone,code);
            return R.success("验证码发送成功！");
        }
        return R.error("验证码发送失败！");

    }


    @PostMapping("/login")
    public R login(@RequestBody Map map,HttpSession session){
        //获取验证码
        String phone =  map.get("phone").toString();
        String code = map.get("code").toString();
        //获取真实的验证码
        String realCode = (String) session.getAttribute(phone);
        //和真实的验证码进行比对
        if(code.equals(realCode)){
            //登录成功
            //看数据库表中是否有数据
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User user1 = userService.getOne(qw);
            if(user1==null){
                //将用户信息存储到user表中
                user1 = new User();
                user1.setPhone(phone);
                user1.setStatus(1);
                userService.save(user1);
            }

            //将用户信息存储到session中
            session.setAttribute("loginUser",user1);

            return R.success(user1);
        }
            return R.error("登录失败");

    }

    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        session.removeAttribute("loginUser");
        return R.success("退出成功！");
    }
}
